import LocalStorage from '@/utils/localStorage'

// import dayjs from 'dayjs'

export interface UserInfo {
    /** token */
    accessToken?: string
    /** `accessToken`的过期时间（时间戳） */
    expires?: string | number
    /** 用于调用刷新accessToken的接口时所需的token */
    refreshToken?: string
    /** token类型 */
    tokenType?: string
    /** 用户名 */
    username?: string
    /** 昵称 */
    name?: string
    /** 当前登陆用户的角色 */
    roles?: Array<string>
    /** 用户头像 */
    avatar?: string
    [prop: string]: any
}
/** 系统前缀 */
export const SYSTEM_PREFIX = 'XYZ_GIS_'
/** token值 */
export const TOKEN_KEY = `${SYSTEM_PREFIX}AccessToken`
/** 过期时间 */
export const XYZ_ACCESS_TOKEN_EXP = `${SYSTEM_PREFIX}AccessTokenExp`
/** token类型 */
export const XYZ_ACCESS_TOKEN_TYPE = `${SYSTEM_PREFIX}AccessTokenType`
/** 刷新token */
export const XYZ_REFRESH_TOKEN = `${SYSTEM_PREFIX}RefreshToken`
/** 用户信息 */
export const USER_INFO_KEY = `${SYSTEM_PREFIX}UserInfo`
/** RBAC的用户菜单 */
export const XYZ_RBAC_MENUS = `${SYSTEM_PREFIX}RbacMenus`

/**
 * @description 用户权限工具类
 */
export default class UserAuth {
    /**
     * 获取用户token
     * @return {string}
     */
    static getToken() {
        return LocalStorage.getItem<string>(TOKEN_KEY)
    }

    /**
     * 设置用户token
     * @param {string} token
     */
    static setToken(token: string) {
        return LocalStorage.setItem(TOKEN_KEY, token)
    }

    /**
     * 删除用户token
     */
    static removeToken() {
        return LocalStorage.removeItem(TOKEN_KEY)
    }

    /**
     * 设置用户信息
     * @param {UserInfo} userInfo
     */
    static setUserInfo(userInfo: UserInfo) {
        const { accessToken, expires, refreshToken, tokenType, ...rest } = userInfo as UserInfo
        LocalStorage.setItem(USER_INFO_KEY, JSON.stringify(rest))
        LocalStorage.setItem(TOKEN_KEY, accessToken)
        LocalStorage.setItem(XYZ_ACCESS_TOKEN_EXP, expires)
        LocalStorage.setItem(XYZ_ACCESS_TOKEN_TYPE, tokenType)
        LocalStorage.setItem(XYZ_REFRESH_TOKEN, refreshToken)
    }

    /**
     * 获取用户信息
     * @return {UserInfo}
     */
    static getUserInfo(): UserInfo {
        return {
            ...LocalStorage.getItem<UserInfo>(USER_INFO_KEY),
            accessToken: LocalStorage.getItem(TOKEN_KEY),
            expires: LocalStorage.getItem(XYZ_ACCESS_TOKEN_EXP),
            tokenType: LocalStorage.getItem(XYZ_ACCESS_TOKEN_TYPE),
            refreshToken: LocalStorage.getItem(XYZ_REFRESH_TOKEN),
        }
    }

    /**
     * 删除用户信息
     */
    static removeUserInfo() {
        LocalStorage.removeItem(USER_INFO_KEY)
        LocalStorage.removeItem(TOKEN_KEY)
        LocalStorage.removeItem(XYZ_ACCESS_TOKEN_EXP)
        LocalStorage.removeItem(XYZ_ACCESS_TOKEN_TYPE)
        LocalStorage.removeItem(XYZ_REFRESH_TOKEN)
    }
}
